package scaladuct.lists

import java.util.{ArrayList, EnumSet}
import scaladuct.{RefInfo, LookupFunctions, Property, MetaCookie}

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Dec 13, 2010
 * Time: 6:48:43 PM
 */

trait DefaultListsManager extends ListsManager {
  val metaCookie: MetaCookie
  val primaryListsManager: ListsManager
  val lookupFn: LookupFunctions.LookupFunction

  def listForProperty(property: Property[AnyRef]): Option[ListForProperty[AnyRef]] = {

    def getDefaultListForEnum: Option[ListForProperty[AnyRef]] = {
      metaCookie.property(property.name) match {
        case Some(argProp) => {
          if (argProp.clazz[Any].isEnum) {

            def createEnumSet[E <: Enum[E]](): EnumSet[E] = {
              EnumSet.allOf(argProp.clazz.asInstanceOf[Class[E]])
            }

            val enumSet: EnumSet[_] = createEnumSet()
            Some(new ListForProperty[AnyRef](property, enumSet.asInstanceOf[java.lang.Iterable[AnyRef]], false, false))
          } else {
            None
          }
        }
        case None => None
      }
    }

    def getDefaultListForReference() = {
      val list = new ArrayList[AnyRef]()
      val refInfo: RefInfo = property.refTypeInfo
      lookupFn(refInfo).foreach(pageFn => list.add(pageFn.toString))
      if (list.isEmpty)
        None
      else if (refInfo.collection)
        Some(new ListForProperty[AnyRef](property, list, false, true))
      else
        Some(new ListForProperty[AnyRef](property, list, false, false))
    }

    def getDefaultListForProperty() = if (property.refTypeInfo != null)
      getDefaultListForReference
    else
      getDefaultListForEnum

    if (primaryListsManager != null) {
      primaryListsManager.listForProperty(property) match {
        case Some(listForProp) => Some(listForProp)
        case None => getDefaultListForProperty
      }
    } else getDefaultListForProperty

  }
}